<template>
  <basic-dialog :visible="show"
                minWidth="780px"
                :title="`阈值${this.statusList[4].label}设置`"
                :isShowClose="false"
                :isFullScreen="false"
                :isShowBasicFooter="true"
                @close="$emit('close')"
                :loading="isSubmitting"
                @submit="submit">
    <q-card-section class="margin-b-10">
      <q-table
        :data="tableData"
        :columns="columns"
        row-key="id"
        hide-bottom
        class="stick-last-col"
        separator="cell"
        no-data-label="暂无数据"
        :pagination="{rowsPerPage: 0}"
        color="primary"
      >
        <template v-slot:no-data>
          <div class="full-width row flex-center font-size-14" style="color: #999">
            暂无数据
          </div>
        </template>
        <template v-slot:body-cell-name="{ row }">
          <q-td>
            <q-select
                      :disable="!String(row.id).startsWith('__')"
                      v-model="row.label"
                      :options="row.msgGroups || nameOptions"
                      dense
                      options-dense
                      lazy-rules
                      class="form-select"
                      emit-value
                      ref="yzInput"
                      map-options
                      outlined>
              <template v-slot:no-option>
                <div class="no-option" />
              </template>
            </q-select>
          </q-td>
        </template>
        <template v-slot:body-cell-pointCondition="{ row }">
          <q-td>
            <q-select
              :disable="!row.set"
              v-model="row.pointCondition"
              :options="conditionOptions"
              dense
              options-dense
              lazy-rules
              class="form-select"
              emit-value
              ref="yzInput"
              map-options
              outlined>
              <template v-slot:no-option>
                <div class="no-option" />
              </template>
            </q-select>
          </q-td>
        </template>
        <template v-slot:body-cell-threshold="{ row }">
          <q-td>
            <div class="flex">
              <q-input
                :disable="!row.set"
                style="width: 80px"
                class="margin-r-15"
                v-model="row.avalue"
                v-if="showA(row)"
                dense
                emit-value
                map-options
                outlined>
              </q-input>
              <q-input
                :disable="!row.set"
                style="width: 80px"
                v-model="row.bvalue"
                dense
                v-if="showB(row)"
                emit-value
                map-options
                outlined>
              </q-input>
              <div v-if="!showA(row) && !showB(row)">--</div>
            </div>
          </q-td>
        </template>
        <template v-slot:body-cell-operations="props">
          <q-td class="operations" style="width: 100px">
            <q-btn flat dense round color="primary" icon="iconfont icontubiao-12"  @click="editRule(props.row)">
              <q-tooltip>编辑</q-tooltip>
            </q-btn>
            <q-btn flat dense round color="primary" icon="iconfont icontubiao-16" @click="deleteRule(props.row)">
              <q-tooltip>删除</q-tooltip>
            </q-btn>
          </q-td>
        </template>
      </q-table>
      <div class="add-wrapper" v-if="showAddIcon" @click="addRule">
        <q-icon name="iconfont icontubiao-39" class="margin-r-10" />添加
      </div>
    </q-card-section>
  </basic-dialog>
</template>

<script>
import { deletePlcSet, getListPlcWarnKey, getPlcWarnSet, setPlcWarnSet } from '../../../boot/status-monitor/machine'
import { mapGetters } from 'vuex'

export default {
  name: 'plc-set-dialog',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    processData: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      isSubmitting: false,
      showAddIcon: true,
      tableData: [],
      nameOptions: [],
      conditionOptions: [
        { label: '数值大于A且小于B', value: 1 },
        // { label: '开关OFF', value: 2 },
        // { label: '开关ON', value: 3 },
        { label: '数值小于A', value: 4 },
        { label: '数值大于B', value: 5 },
        { label: '数值小于A或大于B', value: 6 },
        { label: '数值等于A', value: 7 }
      ],
      columns: [
        { name: 'name', label: '阈值名称', align: 'left', field: 'name' },
        { name: 'pointCondition', label: '触发条件', align: 'left', field: 'pointCondition' },
        { name: 'threshold', label: '触发阈值', align: 'left', field: 'threshold' },
        { name: 'operations', label: '操作', align: 'left', field: 'operations' }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'userInfo', 'statusList'
    ])
  },
  watch: {
    show (val) {
      if (val) {
        this.getPlcWarn()
      }
    }
  },
  methods: {
    editRule (row) {
      row.set = true
    },
    // 提交数据
    submit () {
      // 如果没数据的话
      if (this.tableData.length === 0) {
        this.$message.warning('请设置阈值报警')
        return
      }
      // 检验阈值是否设置
      const check = this.tableData.every(item => {
        if (!item.label) {
          this.$message.warning('请选择阈值名称')
          return false
        }
        if (isNaN(item.avalue) || isNaN(item.bvalue)) {
          this.$message.warning('请输入数字')
          return false
        }
        return true
      })
      if (!check) {
        return
      }
      const params = []
      // 构建数据
      this.tableData.forEach(item => {
        params.push({
          'avalue': item.avalue,
          'bvalue': item.bvalue,
          'deviceId': this.processData.id,
          'id': item.id.startsWith('__') ? '' : item.id,
          'label': item.label,
          'pointCondition': item.pointCondition,
          'pointKeyId': item.name
        })
      })
      this.isSubmitting = true
      setPlcWarnSet(params).then(res => {
        this.$message.success('操作成功')
        this.$emit('close')
      }).finally(() => {
        this.isSubmitting = false
      })
    },
    // 是否显示a输入框
    showA (row) {
      const aArr = [1, 4, 6, 7]
      return aArr.indexOf(row.pointCondition) > -1
    },
    // 是否显示B输入框
    showB (row) {
      const bArr = [1, 5, 6]
      return bArr.indexOf(row.pointCondition) > -1
    },
    // 获取plc阈值名称下拉框
    getPlcWarn () {
      const params = {
        deviceId: this.processData.id,
        tenantId: this.userInfo.tenant_id
      }
      getListPlcWarnKey(this.processData.id).then(res => {
        if (res?.data?.length > 0) {
          this.nameOptions = res.data.map(item => {
            return {
              ...item,
              value: item.label
            }
          })
        }
      })
      // 获取已经设置的表格数据
      getPlcWarnSet(params).then(res => {
        this.tableData = res.data.map(item => {
          return {
            ...item,
            set: false,
            name: item.pointKeyId
          }
        })
      })
    },
    // 添加一条数据
    addRule () {
      // 制造伪id，防止表格循环报错
      const id = '__' + Math.random().toString(36).substr(2, 9)
      const ids = this.tableData.map(item => item.label)
      const msgGroups = this.nameOptions.filter(item => ids.indexOf(item.label) === -1) || []
      const rowData = { id: id, pointCondition: 1, avalue: 0, bvalue: 0, set: true, msgGroups: msgGroups }
      this.tableData.push(rowData)
    },
    // 删除数据
    deleteRule (row) {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>确认删除该条信息吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        // 如果是虚拟id就前端删除 否则就请求后端接口并删除
        if (!row.id.startsWith('__')) {
          deletePlcSet(row.id).then(() => {
            const index = row.__index
            this.tableData.splice(index, 1)
          })
        } else {
          const index = row.__index
          this.tableData.splice(index, 1)
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.add-wrapper{
  width: 100%;
  height: 48px;
  background: #F3F3F3;
  border-radius: 0px 0px 6px 6px;
  font-size: 14px;
  font-weight: 500;
  color: #5F77FD;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
</style>
